<script setup>
import {getConNotifyMessagePageList, getContractBasicInfo, markConMessage} from "@/api/contract/notifyMessage.js";
import router from "@/router/index.js";
import useLoginUserStore from "@/store/modules/user.js";
import {onActivatedFunctions} from "@/utils/common.js";

const {proxy} = getCurrentInstance()
const uniqueId = ref("")
const loginUserStore = useLoginUserStore()
const messageList = ref([])
const loading = ref(false)
const showSearch = ref(true)
const total = ref(0)
const allSelectedIds = ref([])
const multipleSelection = ref([])
const allOperatedList = ref([])

const props = defineProps({
  status: {
    type: String
  },
  notifyMessageStatus: {
    type: Array
  }
})
// 列显隐信息
const columns = ref({
  message: {key: 'name', label: `消息内容`, visible: true},
  createTime: {key: 'createTime', label: `通知时间`, visible: true},
  status: {key: 'status', label: `状态`, visible: true}
})
const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    dateRange: [],
    message: undefined,
    status: props.status,
  }
})
const {queryParams} = toRefs(data)

onMounted(() => {
  getList()
})

onActivatedFunctions(getList, uniqueId)

function getList() {
  loading.value = true
  getConNotifyMessagePageList(proxy.addDateRange(queryParams.value)).then(res => {
    loading.value = false
    messageList.value = res.list
    allOperatedList.value = res.list.filter(item => {
      return item.status === '未读'
    })
    total.value = res.total
  })
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1
  getList()
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm("queryRef")
  queryParams.value.dateRange = []
  handleQuery()
}

defineExpose({
  resetQuery
})

const selectAll = computed({
  get: () => multipleSelection.value.length === allOperatedList.value.filter(item => item.status === '未读' && multipleSelection.value.includes(item)).length,
  set: value => {
    if (value) {
      multipleSelection.value = allOperatedList.value.filter(item => item.status === '未读')
    } else {
      multipleSelection.value = []
    }
  }
})

const isIndeterminate = computed(() => {
  const checkedCount = multipleSelection.value.length
  const totalCount = allOperatedList.value.filter(item => item.status === '未读').length
  return checkedCount > 0 && checkedCount < totalCount
})

function handleSelectionChange(value) {
  multipleSelection.value = value
}

function handleSelectAllChange(value) {
  selectAll.value = value
}

function selectable(row, index) {
  return row.status === '未读'
}

/** 标记为已读 */
function handleUpdate(row, isOpenContractView) {
  allSelectedIds.value = [row.id]
  const conId = row.conId
  if (isOpenContractView) {
    if (row.status !== '已读') {
      markConMessage(allSelectedIds.value)
    }
    getContractBasicInfo(conId).then((contract) => {
      if (contract.userId === loginUserStore.id) {
        router.push({path: '/contract/my/view/' + conId, query: {customTitle: '我的合同 - ' + contract.name}})
      } else {
        if (contract.operatorId === loginUserStore.id) {
          router.push({
            path: "/contract/process/view/" + conId,
            query: {customTitle: '待办合同 - ' + contract.name, status: '待办'}
          })
        } else {
          router.push({
            path: "/contract/process/view/" + conId,
            query: {customTitle: '已办合同 - ' + contract.name, status: '已办'}
          })
        }
      }
    })
    getList()
  } else {
    proxy.$modal.confirmAndExecuteJS('确认标记当前记录为已读?', markConMessage, allSelectedIds.value, getList)
  }
}

function batchMark() {
  if (multipleSelection.value.length === 0) {
    proxy.$modal.msgWarning('请先勾选要标记的消息记录')
    return
  }
  allSelectedIds.value = []
  multipleSelection.value.map((item, index) => {
    allSelectedIds.value.push(item.id)
  })
  proxy.$modal.confirmAndExecuteJS('确认批量标记当前选中的记录为已读?', markConMessage, allSelectedIds.value, getList)
}

</script>

<template>
  <el-form :model="queryParams" ref="queryRef" :inline="true" label-width="92px">
    <el-row :gutter="10" v-show="showSearch">
      <el-form-item label="消息内容" prop="message">
        <el-input
            v-model="queryParams.message"
            placeholder="消息内容"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
        />
      </el-form-item>
      <el-form-item label="通知时间" style="width: 332px;">
        <el-date-picker
            v-model="queryParams.dateRange"
            value-format="YYYY-MM-DD"
            type="daterange"
            range-separator="-"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
        ></el-date-picker>
      </el-form-item>
      <el-form-item label="消息状态" prop="status" v-show="status===''" >
        <el-select
            v-model="queryParams.status"
            placeholder="消息状态"
            clearable
            style="width: 240px"
            :empty-values="[null, undefined]"
        >
          <el-option
              v-for="status in notifyMessageStatus"
              :key="status.value"
              :label="status.label"
              :value="status.value"
          />
        </el-select>
      </el-form-item>
    </el-row>
  </el-form>
  <el-row :gutter="10" class="mb10 mr5">
    <el-col :span="1.5" v-show="showSearch">
      <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
    </el-col>
    <el-col :span="1.5" v-show="showSearch">
      <el-button icon="Refresh" @click="resetQuery">重置</el-button>
    </el-col>
    <el-col :span="1.5" v-show="showSearch" v-if="(status === '' || status === '未读') && (messageList.length > 0)">
      <el-button icon="Check" @click="batchMark">批量标记为已读</el-button>
    </el-col>
    <right-toolbar v-model:showSearch="showSearch" @queryTable="getList" :columns="columns" v-show="total > 0" class="mr5"></right-toolbar>
  </el-row>
  <el-table v-loading="loading" :data="messageList" @selection-change="handleSelectionChange" ref="multipleTable">
    <el-table-column
        type="selection"
        width="55"
        :selectable="selectable"
        v-if="(status === '' || status === '未读') && (messageList.length > 0)"
    >
      <template #header="{ store, selectAll }">
        <el-checkbox
            v-model="selectAll.checked"
            @change="handleSelectAllChange"
            :indeterminate="isIndeterminate"
        >
        </el-checkbox>
      </template>
    </el-table-column>
    <el-table-column :label="columns.message.label" key="message" prop="message" v-if="columns.message.visible" :show-overflow-tooltip="true"
                     min-width="200">
      <template #default="scope">
        <el-link @click="handleUpdate(scope.row, true)" type="primary">
          {{ scope.row.message }}
        </el-link>
      </template>
    </el-table-column>
    <el-table-column :label="columns.createTime.label" key="createTime" prop="createTime" v-if="columns.createTime.visible" width="190"/>
    <el-table-column :label="columns.status.label" key="status" prop="status" v-if="columns.status.visible" width="100">
      <template #default="scope">
        <el-text :type="scope.row.status==='未读'?'warning':''"> {{ scope.row.status }}</el-text>
      </template>
    </el-table-column>
    <el-table-column label="操作" align="left" fixed="right" class-name="small-padding fixed-width" width="110" v-if="status!=='已读'">
      <template #default="scope">
        <el-button link type="primary" icon="Edit" @click="handleUpdate(scope.row)"  v-if="scope.row.status!=='已读'">标记为已读</el-button>
      </template>
    </el-table-column>
  </el-table>
  <pagination
      v-show="total > 0"
      :total="total"
      v-model:page="queryParams.pageNum"
      v-model:limit="queryParams.pageSize"
      @pagination="getList"
  />
</template>